﻿Imports Microsoft.SqlServer.Management.Smo
Imports Microsoft.SqlServer.Management.Common
Imports System.Data
Imports System.Data.SqlClient

Public Class frmRestore
    Dim con As SqlConnection
    Dim cmd As SqlCommand
    Dim dread As SqlDataReader
    Private Sub frmRestore_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        server(".\SQLEXPRESS")
    End Sub
    Sub server(ByVal str As String)
        con = New SqlConnection("Data Source=" & str & ";Database=Master;integrated security=SSPI;")
        con.Open()
        cmd = New SqlCommand("select *  from sysservers  where srvproduct='SQL Server'", con)
        dread = cmd.ExecuteReader
        While dread.Read
            cmbServername.Items.Add(dread(2))
        End While
        dread.Close()
    End Sub

    Sub connection()
        con = New SqlConnection("Data Source=" & Trim(cmbServername.Text) & ";Database=Master;integrated security=SSPI;")
        con.Open()
        cmbDatabase.Items.Clear()
        cmd = New SqlCommand("select * from sysdatabases", con)
        dread = cmd.ExecuteReader
        While dread.Read
            cmbDatabase.Items.Add(dread(0))
        End While
        dread.Close()
    End Sub

    Private Sub cmbServername_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbServername.SelectedIndexChanged
        connection()
    End Sub

    Sub query(ByVal que As String)
        On Error Resume Next
        cmd = New SqlCommand(que, con)
        cmd.ExecuteNonQuery()
    End Sub

    Sub blank(ByVal str As String)

        If cmbServername.Text = "" Or cmbDatabase.Text = "" Then
            MsgBox("Server Name & Database không được để trống!")
            Exit Sub
        Else
            If str = "restore" Then
                Dim o As String
                o = OpenFileDialog1.FileName
                query("RESTORE DATABASE [" & cmbDatabase.Text & "] FROM disk='" & o & "'")

                MsgBox("Bạn có thể tìm thấy tập tin ở " & o)
            End If
        End If
    End Sub

    Private Sub btnDuongDan_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDuongDan.Click
        OpenFileDialog1.Title = "Chọn đường dẫn sao lưu dữ liệu!"
        OpenFileDialog1.Filter = "Tập tin sao lưu (*.bak)|*.bak"
        OpenFileDialog1.ShowDialog()
        txtDuongDan.Text = OpenFileDialog1.FileName
    End Sub

    Private Sub btnOK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOK.Click
        blank("restore")
    End Sub

    Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        Me.Close()
    End Sub
End Class